﻿#define _DEBUG
using System;
using System.Collections.Generic;
using EHR18.Models;
using System.Linq;
using EHR18;

namespace Common
{
    public class T6418 : Product
    {
        private static readonly GenneralConfig G_Config = GenneralConfig.instance;
        I_IO_Card instance = IOFactory.getIO_Instance(G_Config.IO_TYPE);
        public TBAll table = new TBAll();
        public T6418()
        {
            table.MO = G_Config.MO;
            table.Operator = G_Config.OperID;
            table.Model = G_Config.CurrentModel;
            table.TEST_TIME = DateTime.Now;
            table.Result = true;
        }
        public override int Test()
        {
            if (Location >= TestItems.Count)
            {
                LogHelper.WriteLog(typeof(Product), "测试值超出索引");
                return 0;
            }
            TestItem item = TestItems[Location];
            ShowMsg("测试项目:" + item.Name);
            if (item.IsUse)
            {
                //   ShowMsg("测试序列号:" + Location.ToString());
                ShowMsg("产品:" + GetGUID());
                //   ShowMsg("测试点位:" + item.Location.ToString());
                ShowMsg("测试使能状态:" + item.IsUse.ToString());
                int IOLocation = item.Location;

                //    bool bState = instance.ReadBit((uint)IOLocation);
                bool bState = (instance.tag & (1 << IOLocation)) > 0;
                bool result;
                try
                {
                    result = Test(item.Name, bState);
                }
                catch (Exception ex)
                {
                    LogHelper.WriteLog(typeof(T6418), ex);
                    table.Result = false;
                    result = false;
                }
                if (result)
                {
                    ShowMsg("[测试结果]: [PASS]");
                    table.Result = true;
                    return 1;
                }
                else
                {
                    ShowMsg("[测试结果]: [FAIL]");
                    SetFail();
                    table.Result = false;
                    return -1;
                }
            }
            else
            {
                ShowMsg("[测试结果]: [未测试]");
                return 0;
            }
        }

        public override void InsertTable()
        {
            try
            {
                TBAllService.insert(table);
            }
            catch
            {
            }
        }

        private bool Test(string TestFuncName, bool bState)
        {
            if (TestFuncName.Contains("耐压"))
            {
                bState = !bState;
                ShowMsg(string.Format("[{0}结果]:{1}", TestFuncName, (bState ? "失败" : "成功")));
                string strIndex = TestFuncName.Substring(TestFuncName.Length - 1, 1);
                int index = int.Parse(strIndex);
                if (bState)
                {
                    CountManager.AddFail(TestFuncName);
                }
                else
                {
                    CountManager.AddPass(TestFuncName);
                }
                List<TestSpan> tss = new List<TestSpan>();
                TestSpan ts = new TestSpan();
                ts.测试结果 = (bState ? "FAIL" : "PASS");
                ts.测试项目 = TestFuncName.Trim('"');
                ts.测试值 = (bState ? "FAIL" : "PASS");
                ts.上限值 = "NA";
                ts.下限值 = "NA";
                ts.不良数量 = CountManager.getCount(TestFuncName).NG.ToString();
                ts.不良率 = CountManager.getCount(TestFuncName).NgRate;
                ts.测试次数 = CountManager.getCount(TestFuncName).Total.ToString();
                tss.Add(ts);
                table.LIST.Add(new Section { Station = TestFuncName, Item = ts.测试项目, SubInfo = "Max", Value = ts.上限值 });
                table.LIST.Add(new Section { Station = TestFuncName, Item = ts.测试项目, SubInfo = "Min", Value = ts.下限值 });
                table.LIST.Add(new Section { Station = TestFuncName, Item = ts.测试项目, SubInfo = "Value", Value = ts.测试值 });
                table.LIST.Add(new Section { Station = TestFuncName, Item = ts.测试项目, SubInfo = "Result", Value = ts.测试结果 });
                //    table.LIST.Add(ts);
                ShowTestSpan(tss);
                return bState ? false : true;
            }
            else if (TestFuncName.Contains("漏感"))
            {
                // string filePath=
                ShowMsg("开始解析TTS数据");
                string lgPath = "";
                if (TestFuncName == "漏感1")
                {
                    lgPath = GenneralConfig.instance.module.LG_Path1;
                }
                else if (TestFuncName == "漏感2")
                {
                    lgPath = GenneralConfig.instance.module.LG_Path2;
                }
                LGParser ps = new LGParser(lgPath);
                if (ps.Result)
                {
                    CountManager.AddPass(TestFuncName);
                }
                else
                {
                    CountManager.AddFail(TestFuncName);
                }
                var ts = new TestSpan()
                {
                    不良率 = CountManager.getCount(TestFuncName).NgRate,
                    不良数量 = CountManager.getCount(TestFuncName).NG.ToString(),
                    测试次数 = CountManager.getCount(TestFuncName).Total.ToString(),
                    测试结果 = ps.Result ? "PASS" : "FAIL",
                    测试项目 = TestFuncName,
                    测试值 = ps.Value.ToString(),
                    上限值 = ps.UpperValue.ToString(),
                    下限值 = ps.LowerValue.ToString(),
                    单位 = ps.Unit
                };
                List<TestSpan> spns = new List<TestSpan>() { ts };
                ShowTestSpan(spns);
                table.LIST.Add(new Section { Station = TestFuncName, Item = ts.测试项目, SubInfo = "Max", Value = ts.上限值 });
                table.LIST.Add(new Section { Station = TestFuncName, Item = ts.测试项目, SubInfo = "Min", Value = ts.下限值 });
                table.LIST.Add(new Section { Station = TestFuncName, Item = ts.测试项目, SubInfo = "Value", Value = ts.测试值 });
                table.LIST.Add(new Section { Station = TestFuncName, Item = ts.测试项目, SubInfo = "Result", Value = ts.测试结果 });
                return ps.Result;
            }
            else if (TestFuncName.Contains("TTS"))
            {
                ShowMsg("开始解析TTS数据");
                string Dir = GenneralConfig.instance.module.ATR_Path;
                string fileName;
                System.Threading.Thread.Sleep(200);
                if (TTSParser.GetTTSFileName(Dir, DateTime.Now, out fileName))
                {
                    if (TTSParser.conditon == null)
                    {
                        TTSParser.conditon = new TTSConditionParser(fileName);
                    }
                    TTSParser ps = new TTSParser(fileName);
                    if (!ps.Result)
                    {
                        CountManager.AddFail(TestFuncName);
                    }
                    else
                    {
                        CountManager.AddPass(TestFuncName);
                    }
                    List<TestSpan> spns = new List<TestSpan>(){
                        new TestSpan(){
                             不良率=CountManager.getCount(TestFuncName).NgRate,
                             不良数量=CountManager.getCount(TestFuncName).NG.ToString() ,
                                 测试次数 = CountManager.getCount(TestFuncName).Total.ToString(),
                             测试结果=ps.Result?"PASS":"FAIL",
                             测试项目=TestFuncName,
                             测试值=ps.Result?"PASS":"FAIL",
                             上限值="NA",
                             下限值="NA"
                        }};

                    spns.AddRange(ps.TestSpans);
                    foreach (var ts in spns)
                    {
                        table.LIST.Add(new Section { Station = TestFuncName, Item = ts.测试项目, SubInfo = "Max", Value = ts.上限值 });
                        table.LIST.Add(new Section { Station = TestFuncName, Item = ts.测试项目, SubInfo = "Min", Value = ts.下限值 });
                        table.LIST.Add(new Section { Station = TestFuncName, Item = ts.测试项目, SubInfo = "Value", Value = ts.测试值 });
                        table.LIST.Add(new Section { Station = TestFuncName, Item = ts.测试项目, SubInfo = "Result", Value = ts.测试结果 });
                    }
                    ShowTestSpan(spns);
                    return ps.Result;
                }
                else
                {
                    throw new Exception("未找到tts文件");
                }
            }
            else if (TestFuncName.Contains("综测"))
            {
                ShowMsg("开始解析综测数据");
                System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"^[\+\-\dEe\.]+$");
                System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
                sw.Start();
                string AtrPath = G_Config.module.ATR_Path;
                string filePath;
                if (!AtrParser.GetAtrFileName(AtrPath, out filePath, DateTime.Now))
                {
                    if (AtrParser.GetAtrFileName(AtrPath, out filePath, DateTime.Now.AddDays(-1)) == false)
                    {
                        string pattern = string.Format(@"C*{0}.atr", DateTime.Now.ToString("ddMMyy"));
                        var fileName = System.IO.Path.Combine(AtrPath, pattern);
                        ShowMsg("综测文件不存在:" + fileName);
                        return false;
                    }
                }
                AtrParser atr = new AtrParser(filePath);
                List<TestSpan> spans = new List<TestSpan>();
                bool result = atr.getTestSpans(ref spans);
                foreach (TestSpan ts in spans)
                {
                    if (ts.测试项目.Contains("LS"))
                    {
                        int Multiple = G_Config.module.LS_Multiple; /*int.Parse(ConfigurationManager.AppSettings["LS_Multiple"])*/;
                        if (regex.IsMatch(ts.测试值))
                            ts.测试值 = Math.Round(ChangeDataToD(ts.测试值), 3).ToString();
                        if (regex.IsMatch(ts.上限值))
                            ts.上限值 = Math.Round(ChangeDataToD(ts.上限值), 3).ToString();
                        if (regex.IsMatch(ts.下限值))
                            ts.下限值 = Math.Round(ChangeDataToD(ts.下限值), 3).ToString();

                    }
                    else if (ts.测试项目.Contains("TR"))
                    {
                        if (regex.IsMatch(ts.测试值))
                            ts.测试值 = Math.Round(ChangeDataToD(ts.测试值), 3).ToString();
                        if (regex.IsMatch(ts.上限值))
                            ts.上限值 = Math.Round(ChangeDataToD(ts.上限值), 3).ToString();
                        if (regex.IsMatch(ts.下限值))
                            ts.下限值 = Math.Round(ChangeDataToD(ts.下限值), 3).ToString();

                    }
                    else if (ts.测试项目.Contains("SURG"))
                    {
                        int Multiple = G_Config.module.SURG_Multiple;
                        if (regex.IsMatch(ts.测试值))
                            ts.测试值 = Math.Round(ChangeDataToD(ts.测试值), 3).ToString();
                        if (regex.IsMatch(ts.上限值))
                            ts.上限值 = Math.Round(ChangeDataToD(ts.上限值), 3).ToString();
                        if (regex.IsMatch(ts.下限值))
                            ts.下限值 = Math.Round(ChangeDataToD(ts.下限值), 3).ToString();

                    }
                    else if (ts.测试项目.Contains("R"))
                    {
                        float Multiple = G_Config.module.R_Multiple;
                        if (regex.IsMatch(ts.测试值))
                            ts.测试值 = Math.Round(ChangeDataToD(ts.测试值), 3).ToString();
                        if (regex.IsMatch(ts.上限值))
                            ts.上限值 = Math.Round(ChangeDataToD(ts.上限值), 3).ToString();
                        if (regex.IsMatch(ts.下限值))
                            ts.下限值 = Math.Round(ChangeDataToD(ts.下限值), 3).ToString();

                    }
                    else if (ts.测试项目.Contains("CTY"))
                    {


                    }
                    else if (ts.测试项目.Contains("LVOC"))
                    {
                        float Multiple = G_Config.module.LVOC_Multiple;
                        if (regex.IsMatch(ts.测试值))
                            ts.测试值 = Math.Round(ChangeDataToD(ts.测试值), 3).ToString();
                        if (regex.IsMatch(ts.上限值))
                            ts.上限值 = Math.Round(ChangeDataToD(ts.上限值), 3).ToString();
                        if (regex.IsMatch(ts.下限值))
                            ts.下限值 = Math.Round(ChangeDataToD(ts.下限值), 3).ToString();
                    }
                    table.LIST.Add(new Section { Station = TestFuncName, Item = ts.测试项目, SubInfo = "Max", Value = ts.上限值 });
                    table.LIST.Add(new Section { Station = TestFuncName, Item = ts.测试项目, SubInfo = "Min", Value = ts.下限值 });
                    table.LIST.Add(new Section { Station = TestFuncName, Item = ts.测试项目, SubInfo = "Value", Value = ts.测试值 });
                    table.LIST.Add(new Section { Station = TestFuncName, Item = ts.测试项目, SubInfo = "Result", Value = ts.测试结果 });
                }
                spans.Reverse();
                ShowTestSpan(spans);
                sw.Stop();
                table.LIST.Add(new Section { Station = TestFuncName, Item = "Final", SubInfo = "Result", Value = result ? "PASS" : "FAIL" });
                LogHelper.WriteLog(typeof(Product), string.Format("读取ATR文件用的时间 {0} ms", sw.ElapsedMilliseconds));
                if (!result)
                {
                    ShowMsg("[综测结果]:失败");
                    SetFail();
                    return false;
                }
                else
                {
                    ShowMsg("[综测结果]:成功");
                    return true;
                }

            }
            else if (TestFuncName.Contains("图像"))
            {
                bool ret;
                int iStart = Environment.TickCount;
                try
                {
                    string CCDPath = G_Config.module.CCD_Path;
                    string filePath = string.Format(@"{0}\{1}.csv", CCDPath, DateTime.Now.ToString("yyyyMMdd"));
                    CCDParser cpr = new CCDParser(filePath);
                    List<Section> sections = new List<Section>();
                    ret = cpr.getSpans(ref sections);
                    table.LIST.AddRange(sections);

                    if (ret)
                    {
                        CountManager.AddPass(TestFuncName);
                        ShowMsg("[图像结果]:成功");
                    }
                    else
                    {
                        CountManager.AddFail(TestFuncName);
                        ShowMsg("[图像结果]:失败");

                    }
                    var span = new TestSpan
                    {
                        测试项目 = TestFuncName,
                        上限值 = "NA",
                        下限值 = "NA",
                        不良数量 = CountManager.getCount(TestFuncName).NG.ToString(),

                        不良率 = CountManager.getCount(TestFuncName).NgRate,
                        测试次数 = CountManager.getCount(TestFuncName).Total.ToString(),
                        测试结果 = ret ? "PASS" : "FAIL"
                    };
                    ShowTestSpan(new List<TestSpan> { span });
                    return ret;
                }
                catch (Exception ex)
                {
                    LogHelper.WriteLog(typeof(T6418), ex);
                    return false;
                }
            }
            else if (TestFuncName.Contains("空站"))
            {
                return true;
            }
            else
            {
                ShowMsg("[Error]:没有这个测试项目，请检查配置文件");
                return false;
            }
        }
    }
}
